<?php
/**
 * User: hjd-yao
 * Date: 2019/6/14
 * Time: 11:34
 */

namespace Shop\Http\Controllers\Wap;


use App\Helpers\SelfEncrypt;
use App\Helpers\SelfResponse;
use App\Models\Shop\OrderGoodsModel;
use App\Models\Shop\OrderModel;

use App\Models\Shop\OrderPaymentModel;
use App\Models\Shop\ShopCartModel;
use App\Models\Shop\ShopGoodsModel;
use App\Models\Shop\ShopGoodsSpecValueModel;
use App\Models\Shop\UserAddressModel;
use Carbon\Carbon;
use DC\UserCenter\Models\UserAuthModel;
use DC\UserCenter\Models\UserBaseModel;
use DC\UserCenter\Models\UserWalletModel;
use Illuminate\Http\Request;
use PhpParser\Node\Stmt\Return_;
use Shop\Http\Controllers\BaseController;

use App\Models\System\ConfigModel;
use Yansongda\Pay\Pay;

class OrderController extends BaseController
{
    /**
     * @title 立即购买
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function buyOrder(Request $request)
    {
        $user_id = $request->input('user_id');
        $goods_id = $request->post('goods_id');
        $buy_number = $request->post('buy_number');
        $goods_specs = $request->post('goods_specs');
        $goods = ShopGoodsModel::where('goods_id',$goods_id)->limit(1)->get();
        $zone = 0;
        $total = 0;
        $post_cost = 0;
        $agent_cost = 0;
        $pay_price = 0;
        $buy_num = [];
        $specs = [];
        $goods_ids = [];
        $subtotal = [];
        foreach ($goods as $key=>$item){
            $zone = $item->goods_zone;
            if($goods_specs){
                $goods = ShopGoodsSpecValueModel::init()->where('goods_id',$item->goods_id)->where('goods_spec_items',$goods_specs)->get();
                $goods[$key]->goods_name = $item->goods_name;
                $goods[$key]->goods_images = $item->goods_images;
                $goods[$key]->post_type = $item->post_type;
                $goods[$key]->postage = $item->postage;

                $specs[$item->goods_id] = $goods_specs;
            }
            $goods_price = 0 ;
            $goods_price = $this->getGoodsPrice($user_id,$goods[$key]);

            $total += $goods_price * $buy_number;

            $buy_num[$item->goods_id] = $buy_number;
            $subtotal[$item->goods_id] = $goods_price * $buy_number;
            $goods_ids[] = $item->goods_id;
            $post_cost += $item->postage ;

        }
        $pay_price = $total + $post_cost ;

        $sign = $this->signStr($zone,$goods_ids,[],$specs);
        $this->getPostAddr($user_id);


        return $this->wapRender('order.cart_order',[
            'page_title'=>'确认订单',
            'goods'=>$goods,
            'buy_num'=>$buy_num,
            'specs'=>$specs,
            'wallet'=>UserWalletModel::find($user_id),
            'zone'=>$zone,
            'total'=>$total,
            'pay_price'=>$pay_price,
            'subtotal'=>$subtotal,
            'post_cost'=>$post_cost,
            'agent_cost'=>$agent_cost,
            'sign'=>$sign,
        ]);
    }

    public function buyCart(Request $request,$zone=1)
    {
        $user_id = $request->input('user_id');
        $cart_id = array_filter(str2arr($request->input('cart_id')));
        if(!$cart_id){
            return SelfResponse::error('请选择结算商品！');
        }

        $carts = ShopCartModel::with('goods')->where('goods_zone',$zone)
            ->where('user_id',$user_id)->whereIn('id',$cart_id)->get();

        $total = 0;
        $post_cost = 0;
        $agent_cost = 0;
        $buy_num = [];
        $specs = [];
        $cart_goods = [];
        $cart_ids = [];
        $goods_ids = [];
        $pay_price = 0;
        $subtotal = [];
        foreach ($carts as $item){

            if($item->goods_zone !=$zone){
                continue;
            }

            $goods_ids[] = $item->goods_id;
            $specs[$item->goods_id] = $item->spec_item;

            if($item->spec_item){
                $goods = ShopGoodsSpecValueModel::init()->where('goods_id',$item->goods_id)->where('goods_spec_items',$item->spec_item)->first();
                $goods->goods_name = $item->goods->goods_name;
                $goods->goods_images = $item->goods->goods_images;
                $goods->post_type = $item->goods->post_type;
                $goods->postage = $item->goods->postage;
            }else{
                $goods = ShopGoodsModel::find($item->goods_id);
            }

            $goods_price = 0 ;
            $goods_price = $this->getGoodsPrice($user_id,$goods);

            $buy_num[$item->goods_id] = $item->num;

            $cart_goods[] =$goods;

            $cart_ids[] = $item->id;

            $total += $goods_price * $item->num;
            $subtotal[$item->goods_id] = $goods_price * $item->num;

            $post_cost += $goods->postage;

        }
        $pay_price = $total + $post_cost ;
        $sign = $this->signStr($zone,$goods_ids,$cart_ids,$specs);

        $this->getPostAddr($user_id);

        return $this->view('order.cart_order',[
            'goods'=>$cart_goods,
            'page_title'=>'确认订单',
            'buy_num'=>$buy_num,
            'sign'=>$sign,
            'specs'=>$specs,
            'total'=>$total,
            'subtotal'=>$subtotal,
            'pay_price'=>$pay_price,
            'post_cost'=>$post_cost,
            'agent_cost'=>$agent_cost,
            'cart_id'=>arr2str($cart_ids),
            'wallet'=>UserWalletModel::find($user_id),
            'zone'=>$zone
        ]);
    }

    public function submitOrder(Request $request,$zone=1)
    {
        if($request->isMethod('post')){
            $user_id = $request->input('user_id');
            $remark = $request->post('remark');
            $address = $request->post('address');
            $sign = $request->post('sign');
            $buy_type = $request->post('buy_type',0);
            $pay_type = $request->post('zhifu',0);
            $goods_ids = array_filter(str2arr($request->post('goods_id')));
            $cart_id = array_filter(str2arr($request->post('cart_id',0)));
            $goods_specs= $request->post('specs');
            $buy_number = $request->post('number');

            if(!$goods_ids){
                return SelfResponse::error('请选择购买商品');
            }

            if(!$pay_type){
                return SelfResponse::error('请选择支付方式');
            }

            if($sign != $this->signStr($zone,$goods_ids,$cart_id,$goods_specs)){
                return SelfResponse::error('提交信息被篡改,请保证安全');
            }

            $address = UserAddressModel::where('user_id',$user_id)->find($address);
            if(!$address){
                return SelfResponse::error('请选择收货地址');
            }

            $order_id = OrderModel::init()->createOrder($user_id,$address->toArray(),$remark,$zone);
            if(!$order_id){
                return SelfResponse::error('订单创建失败');
            }

            $goods_cost = 0; //商品话费
            $post_cost = 0;//邮费
            $xf_points = 0;
            $agent_price = 0 ;

//            // 计算 折扣
//            if($zone == 2){
//                $shop_discount = get_rule('shop_discount') ?? 0;
//            }else{
                $shop_discount = 0 ;
//            }
            $dan=0;//报单量
            foreach ($goods_ids as $goods_id){

                $goods_info = ShopGoodsModel::find($goods_id);

                $number = $buy_number[$goods_id]>0?$buy_number[$goods_id]:1;

                $dan+=$goods_info->dan*$number;//报单量

                $spec = $goods_specs[$goods_id];

                if($spec){
                    $goods = ShopGoodsSpecValueModel::init()->where('goods_id',$goods_id)->where('goods_spec_items',$spec)->first();
                    $goods->goods_name = $goods_info->goods_name;
                    $goods->goods_images = $goods_info->goods_images;
                    $goods->post_type = $goods_info->post_type;
                    $goods->postage = $goods_info->postage;
                }else{
                    $goods =  $goods_info ;
                }

                $goods_price = 0;
                $goods_price = $this->getGoodsPrice($user_id,$goods);

                $goods_cost += $goods_price*$number ;

                $post_cost += $goods->postage ;

                OrderGoodsModel::init()->createOrderGoods($order_id,$goods_info->toArray(),$spec,$number,$zone,$buy_type,$goods_price,$shop_discount);
            }


            $xf_points = $goods_cost * $shop_discount * 0.1 ;

            $total_cost = $goods_cost+$post_cost - $xf_points;//应支付

            $pay_price = $total_cost;

            $res = OrderModel::where('order_id',$order_id)->update([
                'goods_price'=>$goods_cost,
                'total_price'=>$total_cost,
                'post_cost'=>$post_cost,
                'pay_price'=>$pay_price,
                'pay_xf_points'=>$xf_points,
                'is_agent'=>$buy_type,
                'pay_type'=>$pay_type,
                'dan'=>$dan
            ]);

            if(!$res){
                OrderModel::where('order_id',$order_id)->delete();
                OrderGoodsModel::where('order_id',$order_id)->delete();
                return SelfResponse::error('订单创建失败');
            }

            $order_sn =  OrderModel::where('order_id',$order_id)->value('order_sn');

            $orderPayment = new OrderPaymentModel();
            $orderPayment->createPayment(0, $order_sn, '', "在线支付订单", $pay_price, 1, $order_id);

            if($cart_id){//清空购物车中的选中产品
                ShopCartModel::where('user_id',$user_id)->whereIn('id',$cart_id)->delete();
            }
            return SelfResponse::success('订单创建成功',['f_Wap_Order_payOrder',['order_id'=>$order_id]]);
        }else{
            return SelfResponse::error('订单创建失败');
        }
    }

    public function getPostAddr($user_id)
    {
        $address = UserAddressModel::init()->getDefault($user_id);

        if($address){
            $address->address = get_address($address->area).'-'.$address->address;
            $all_address = UserAddressModel::where('user_id',$user_id)->orderBy('updated_at','desc')->limit(5)->get();
            foreach ($all_address as $item){
                $item->address = get_address($item->area).'-'.$item->address;
            }
        }
        view()->share('address',$address);
        view()->share('all_addr',$all_address??'');
    }

    private function signStr($zone,$goods_ids,$cart_ids,$specs){
        $data['goods'] =$goods_ids;
        $data['zone'] =$zone;
        if(count($cart_ids)>0){
            $data['cart'] =$cart_ids;
        }
        if(count($specs)>0){
            $data['specs'] =$specs;
        }
        return SelfEncrypt::dataAuthSign($data);
    }


    public function payOrder(Request $request,$order_id)
    {
        $user_id = $request->input('user_id');

        if($request->isMethod('post')){

            $voucher = $request->input('voucher');

            $pay_pwd = $request->input('pay_pwd');
            if($pay_pwd == '' || empty($pay_pwd)){
                return SelfResponse::error('支付密码不能为空');
            }
            if(! UserAuthModel::init()->checkSafePwd($pay_pwd,$user_id)){
                return SelfResponse::error('支付密码输入错误');
            }
            $order = new OrderModel();
           if($order->payOrder($order_id,$user_id,$voucher)){
               OrderGoodsModel::init()->incrementSales($order_id);
               return SelfResponse::success('支付成功','f_Wap_Order_orderRecord');
           }
           return SelfResponse::error($order->getErrorMsg('支付失败'));

        }else{
            $order = OrderModel::where('uid',$user_id)->where('status',0)->find($order_id);
            if(!$order){
                return redirect()->route('f_Shop_index');
            }

            switch ($order->pay_type){
                case 100:
                    $html_blade = "pay_order1";
                    break;
                case 99:
                    $html_blade = "pay_order3";
                    break;
                default:
                    $html_blade = "pay_order2";
                    break;
            }
            return $this->wapRender('order.'.$html_blade,[
                'page_title'=>'收银台',
                'order'=>$order,
                'zone'=>$order->goods_zone,
                'pay_type'=>$order->pay_type,
                'pay_money'=>$order->pay_price,
                'wallet'=>UserWalletModel::find($user_id),
                'order_id'=>$order_id
            ]);
        }
    }



    public function waitPayOrder(Request $request)
    {
        $user_id = $request->input('user_id');
        $pageNum = $request->input('page_num',1);

        $list = OrderModel::with('goods')->where('status',0)
            ->where('uid',$user_id)->forPage($pageNum,$this->perNum())->get();
        return $this->wapRender('order.order_record',[
            'page_title'=>'代付款订单',
            'status'=>0,
            'list'=>$list
        ]);
    }


    public function onlinePayOrder(Request $request){

        $user_id = $request->input('user_id');
        if($request->isMethod('post')){
            $order_id = $request->input('order_id');
            $orderModel = new OrderModel();
            $order = $orderModel->where('uid',$user_id)->where('status',0)->find($order_id);
            if(empty($order) || !$order){
                return view('frontend::login.callback',[
                    'page_title'=>'支付订单获取失败',
                    'status'=>-1,
                    'order_no'=>$order['order_sn']
                ]);
            }

            $pay_type = $request->post('zhifu',0);

            if(!$pay_type){
                return SelfResponse::error('请选择支付方式');
            }

           if($pay_type == 111){

               $aliPayOrder = [
                   'out_trade_no' => $order->order_sn,
                   'total_amount' => $order->pay_price, // 支付金额
                   'subject'      => '支付宝手机支付' // 备注
               ];

               $config = config('pay.alipay');

               $config['return_url'] = $config['return_url'].'?out_trade_no='.$order->order_sn;

               $config['notify_url'] = $config['notify_url'].'?out_trade_no='.$order->order_sn;

               $result = Pay::alipay($config)->wap($aliPayOrder);

               return $result ;

           }elseif($pay_type == 110){

               $data = [
                   'out_trade_no' => $order->order_sn,//订单号
                   'body'          => '微信手机支付',//商品名称
                   'total_fee'      => $order->pay_price * 100//金额单位分
               ];

                $config = config('pay.wechat');
                $config['notify_url'] = $config['notify_url'].'?out_trade_no='.$order->order_sn;//加入回调url
                $result = Pay::wechat($config)->wap($data);//统一下单
//                $json = $result->getContent();
////               $res = json_decode($json);
                return $result ;

           }

        }
    }

    public function orderRecord(Request $request)
    {
        $user_id = $request->input('user_id');
        $status = $request->input('status',false);
        $pageNum = $request->input('page_num',1);

        $model = OrderModel::with('goods')->where('uid',$user_id);
        if($status !== false){
            $model->where('status',$status);
        }

        $list = $model->forPage($pageNum,$this->perNum())->orderBy('created_at','desc')->get();
        return $this->wapRender('order.order_record',[
            'page_title'=>'订单',
            'list'=>$list,
            'status'=>$status,
        ]);
    }

    public function deleteOrder(Request $request)
    {
        $user_id = $request->input('user_id');
        $order_id = $request->input('order_id');
        $order = OrderModel::where('status',0)->where('uid',$user_id)->find($order_id);
        if(!$order){
            return SelfResponse::error('订单不存在');
        }

        if($order->delete()){
            return SelfResponse::success('删除成功','f_Wap_Order_waitPayOrder');
        }

        return SelfResponse::error('删除失败功');
    }

    public function confirmOrder(Request $request)
    {
        $user_id = $request->input('user_id');
        $order_id = $request->input('order_id');
        $order = OrderModel::where('status',2)->where('uid',$user_id)->find($order_id);
        if(!$order){
            return SelfResponse::error('订单不存在');
        }
        $order->status = 3;
        $order->signed_at = Carbon::now()->timestamp;
        if($order->save()){
            return SelfResponse::success('确认成功','f_Wap_Order_waitPayOrder');
        }

        return SelfResponse::error('确认失败');
    }


    /**
     * @title 订单详情
     * @param $order_id
     * @return View
     */
    public function detailOrder(Request $request)
    {
        $user_id = $request->input('user_id');
        $order_id = $request->input('order_id');
        $info = OrderModel::with('goods')->where('uid',$user_id)->find($order_id);

        if(!$info){
            return redirect()->route('f_Wap_Order_orderRecord');
        }

        return $this->wapRender('order.order_detail',[
            'page_title'=>'订单详情',
            'info'=>$info
        ]);
    }

    public function getGoodsPrice($user_id,$goods){
        $level = UserBaseModel::init()->where('member_id',$user_id)->value('level');
        if($level > 0){
            $goods_price = $goods->vip_price ;
        }else{
            $goods_price = $goods->price ;
        }
        return $goods_price ;
    }


    public function DeductionMoney($user_id){

        return 1 ;
    }
}